using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Input;
using System.Threading.Tasks;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using ErpManager.WPF.Models;
using ErpManager.WPF.Services;

namespace ErpManager.WPF.ViewModels
{
    public class DealerViewModel : INotifyPropertyChanged
    {
        private readonly ApplicationDbContext _context;
        private readonly LogService _logService;
        private string _searchText = string.Empty;
        private Dealer? _selectedDealer;
        private string _dealerName = string.Empty;
        private string _contact = string.Empty;
        private string _phone = string.Empty;
        private string _address = string.Empty;
        private string _errorMessage = string.Empty;
        private bool _isLoading;
        private bool _isEditing;

        public ObservableCollection<Dealer> Dealers { get; } = new();

        public event PropertyChangedEventHandler? PropertyChanged;

        public string SearchText
        {
            get => _searchText;
            set
            {
                _searchText = value;
                OnPropertyChanged(nameof(SearchText));
                FilterDealers();
            }
        }

        public Dealer? SelectedDealer
        {
            get => _selectedDealer;
            set
            {
                _selectedDealer = value;
                if (value != null && !IsEditing)
                {
                    DealerName = value.DealerName;
                    Contact = value.Contact;
                    Phone = value.Phone;
                    Address = value.Address;
                }
                OnPropertyChanged(nameof(SelectedDealer));
                OnPropertyChanged(nameof(IsDealerSelected));
            }
        }

        public string DealerName
        {
            get => _dealerName;
            set
            {
                _dealerName = value;
                OnPropertyChanged(nameof(DealerName));
            }
        }

        public string Contact
        {
            get => _contact;
            set
            {
                _contact = value;
                OnPropertyChanged(nameof(Contact));
            }
        }

        public string Phone
        {
            get => _phone;
            set
            {
                _phone = value;
                OnPropertyChanged(nameof(Phone));
            }
        }

        public string Address
        {
            get => _address;
            set
            {
                _address = value;
                OnPropertyChanged(nameof(Address));
            }
        }

        public string ErrorMessage
        {
            get => _errorMessage;
            set
            {
                _errorMessage = value;
                OnPropertyChanged(nameof(ErrorMessage));
            }
        }

        public bool IsLoading
        {
            get => _isLoading;
            set
            {
                _isLoading = value;
                OnPropertyChanged(nameof(IsLoading));
            }
        }

        public bool IsEditing
        {
            get => _isEditing;
            set
            {
                _isEditing = value;
                OnPropertyChanged(nameof(IsEditing));
                OnPropertyChanged(nameof(IsNotEditing));
            }
        }

        public bool IsNotEditing => !IsEditing;
        public bool IsDealerSelected => SelectedDealer != null;

        public ICommand AddDealerCommand { get; }
        public ICommand EditDealerCommand { get; }
        public ICommand SaveDealerCommand { get; }
        public ICommand CancelEditCommand { get; }
        public ICommand DeleteDealerCommand { get; }
        public ICommand RefreshCommand { get; }

        public DealerViewModel(ApplicationDbContext context)
        {
            _context = context;
            _logService = new LogService(context, "system", "系统");
            AddDealerCommand = new RelayCommand(async () => await AddDealer(), CanAddDealer);
            EditDealerCommand = new RelayCommand(() => StartEdit(), () => IsDealerSelected && !IsEditing);
            SaveDealerCommand = new RelayCommand(async () => await SaveDealer(), () => IsEditing && CanSaveDealer());
            CancelEditCommand = new RelayCommand(CancelEdit, () => IsEditing);
            DeleteDealerCommand = new RelayCommand(async () => await DeleteDealer(), () => IsDealerSelected && !IsEditing);
            RefreshCommand = new RelayCommand(async () => await LoadDealers());

            // 初始加载经销商列表
            _ = LoadDealers();
        }

        private async Task LoadDealers()
        {
            try
            {
                IsLoading = true;
                ErrorMessage = string.Empty;

                var dealers = await _context.Dealers
                    .OrderByDescending(d => d.CreateTime)
                    .ToListAsync();

                Dealers.Clear();
                foreach (var dealer in dealers)
                {
                    Dealers.Add(dealer);
                }
            }
            catch (Exception ex)
            {
                ErrorMessage = $"加载经销商列表失败: {ex.Message}";
            }
            finally
            {
                IsLoading = false;
            }
        }

        private void FilterDealers()
        {
            if (string.IsNullOrWhiteSpace(SearchText))
            {
                _ = LoadDealers();
                return;
            }

            var filteredDealers = _context.Dealers
                .Where(d => d.DealerName.Contains(SearchText) || 
                           d.Contact.Contains(SearchText) || 
                           d.Phone.Contains(SearchText))
                .OrderByDescending(d => d.CreateTime)
                .ToList();

            Dealers.Clear();
            foreach (var dealer in filteredDealers)
            {
                Dealers.Add(dealer);
            }
        }

        private async Task AddDealer()
        {
            try
            {
                if (!CanAddDealer())
                {
                    return;
                }

                var dealer = new Dealer
                {
                    DealerName = DealerName.Trim(),
                    Contact = Contact.Trim(),
                    Phone = Phone.Trim(),
                    Address = Address.Trim(),
                    CreateTime = DateTime.Now,
                    UpdateTime = DateTime.Now
                };

                _context.Dealers.Add(dealer);
                await _context.SaveChangesAsync();

                // 记录添加经销商日志
                await _logService.LogOperationAsync("经销商管理", "添加", $"添加经销商：{dealer.DealerName}，联系人：{dealer.Contact}");

                Dealers.Insert(0, dealer);
                ClearForm();
                ErrorMessage = string.Empty;
            }
            catch (Exception ex)
            {
                ErrorMessage = $"添加经销商失败: {ex.Message}";
            }
        }

        private void StartEdit()
        {
            if (SelectedDealer == null) return;
            IsEditing = true;
        }

        private async Task SaveDealer()
        {
            if (SelectedDealer == null || !CanSaveDealer()) return;

            try
            {
                SelectedDealer.DealerName = DealerName.Trim();
                SelectedDealer.Contact = Contact.Trim();
                SelectedDealer.Phone = Phone.Trim();
                SelectedDealer.Address = Address.Trim();
                SelectedDealer.UpdateTime = DateTime.Now;

                _context.Dealers.Update(SelectedDealer);
                await _context.SaveChangesAsync();

                // 记录修改经销商日志
                await _logService.LogOperationAsync("经销商管理", "修改", $"修改经销商：{SelectedDealer.DealerName}，联系人：{SelectedDealer.Contact}");

                IsEditing = false;
                ErrorMessage = string.Empty;

                // 刷新列表中的显示
                var index = Dealers.IndexOf(SelectedDealer);
                if (index != -1)
                {
                    Dealers[index] = SelectedDealer;
                }
            }
            catch (Exception ex)
            {
                ErrorMessage = $"保存经销商失败: {ex.Message}";
            }
        }

        private void CancelEdit()
        {
            if (SelectedDealer != null)
            {
                DealerName = SelectedDealer.DealerName;
                Contact = SelectedDealer.Contact;
                Phone = SelectedDealer.Phone;
                Address = SelectedDealer.Address;
            }
            IsEditing = false;
            ErrorMessage = string.Empty;
        }

        private async Task DeleteDealer()
        {
            if (SelectedDealer == null)
            {
                return;
            }

            try
            {
                var dealerName = SelectedDealer.DealerName;
                var contact = SelectedDealer.Contact;
                _context.Dealers.Remove(SelectedDealer);
                await _context.SaveChangesAsync();

                // 记录删除经销商日志
                await _logService.LogOperationAsync("经销商管理", "删除", $"删除经销商：{dealerName}，联系人：{contact}");

                Dealers.Remove(SelectedDealer);
                SelectedDealer = null;
                ClearForm();
                ErrorMessage = string.Empty;
            }
            catch (Exception ex)
            {
                ErrorMessage = $"删除经销商失败: {ex.Message}";
            }
        }

        private bool CanAddDealer()
        {
            return !string.IsNullOrWhiteSpace(DealerName) &&
                   !string.IsNullOrWhiteSpace(Contact) &&
                   !string.IsNullOrWhiteSpace(Phone) &&
                   !Dealers.Any(d => d.DealerName == DealerName.Trim());
        }

        private bool CanSaveDealer()
        {
            return !string.IsNullOrWhiteSpace(DealerName) &&
                   !string.IsNullOrWhiteSpace(Contact) &&
                   !string.IsNullOrWhiteSpace(Phone) &&
                   (!Dealers.Any(d => d.DealerName == DealerName.Trim() && d.DealerId != SelectedDealer?.DealerId));
        }

        private void ClearForm()
        {
            DealerName = string.Empty;
            Contact = string.Empty;
            Phone = string.Empty;
            Address = string.Empty;
        }

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
